package example1;

import cn.hutool.core.io.resource.ClassPathResource;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.operators.conditional.AndExpression;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.statement.select.*;
import net.sf.jsqlparser.util.TablesNamesFinder;
import org.apache.commons.io.IOUtils;
import org.junit.Test;

import java.io.InputStream;
import java.util.List;

public class SQLTest {
    @Test
    public void t1() throws Exception {

        InputStream stream = new ClassPathResource("file2.txt").getStream();
        String text = IOUtils.toString(stream, "UTF-8");
        System.out.println(text);

        Select select = (Select) CCJSqlParserUtil.parse(text);
        TablesNamesFinder tablesNamesFinder = new TablesNamesFinder();
        List<String> tableList = tablesNamesFinder.getTableList(select);
        System.out.println(tableList);


        PlainSelect plainSelect = (PlainSelect) select.getSelectBody();
        List<SelectItem> selectItems = plainSelect.getSelectItems();
        System.out.println(selectItems);

        Expression where = plainSelect.getWhere();
        System.out.println(where.getClass().getSimpleName());
        if (where instanceof AndExpression) {
            AndExpression and = (AndExpression) where;
            System.out.println(and);
        }

        GroupByElement groupBy = plainSelect.getGroupBy();
        System.out.println(groupBy.getClass().getSimpleName());
        if (groupBy instanceof GroupByElement) {
            GroupByElement group = (GroupByElement) groupBy;
            System.out.println(group);
        }
    }

    @Test
    public void t2() throws Exception {

        InputStream stream = new ClassPathResource("file4.txt").getStream();
        String text = IOUtils.toString(stream, "UTF-8");
        System.out.println(text);

        Select select = (Select) CCJSqlParserUtil.parse(text);
        PlainSelect plainSelect = (PlainSelect) select.getSelectBody();
        List<SelectItem> selectItems = plainSelect.getSelectItems();
        System.out.println(selectItems);


    }

}
